<template>
	<li
		:class="{completed:todo.completed, editing: editedTodo === todo}"
	>
		<div class="view">
			<input
				type="checkbox"			
				v-model="todo.completed"
			>
			<label @dblclick="editTodo(todo)"> {{todo.title}}</label>
			<button @click="removeTodo(todo)">×</button>
		</div>
		<!-- 编辑 -->
		<EditTodo
			class="edit"
			v-model:todo-title="todo.title"
			v-todo-focus="editedTodo === todo"
			@blur="doneTodo(todo)"
			@keyup.esc="cancle(todo)"
			@keyup.enter="doneTodo(todo)"
		></EditTodo>
	</li>
</template>

<script>
	import { reactive, toRefs } from "vue";

	export default {
		props: {
			todo: {
				type: Object,
				required: true,
			},
			editedTodo: Object,
		},
		emits: ["remove-todo", "update:editedTodo"],

		setup(props, { emit }) {
			const state = reactive({
				beforeEdited: "", //编辑之前的值
			});

			function editTodo(todo) {
				state.beforeEdited = todo.title;
				emit("update:editedTodo", todo);
			}
			function doneTodo(todo) {
				emit("update:editedTodo", null);
			}
			function cancle(todo) {
				todo.title = state.beforeEdited;
				emit("update:editedTodo", null);
			}

			function removeTodo(todo) {
				emit("remove-todo", todo);
			}
			return {
				...toRefs(state),
				removeTodo,
				editTodo,
				doneTodo,
				cancle,
			};
		},

		directives: {
			"todo-focus": (el, { value }) => {
				if (value) {
					el.focus();
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.completed label {
		text-decoration: line-through;
	}
	.edit,
	.editing .view {
		display: none;
	}

	.editing .edit {
		display: block;
	}
	input[type="text"] {
		border: 1px solid #dcdcdc;
	}
</style>